package emulator.unittest.hardware.io.peripherals;


import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import emulator.hardware.io.Port6522;
import emulator.hardware.io.peripherals.KeyboardMatrix;

public class KeyboardMatrixTest {

	private KeyboardMatrix matrix;
	private Port6522 portA;
	private Port6522 portB;

	@Before
	public void setUp() throws Exception {
		matrix = new KeyboardMatrix();
		portA = new Port6522();
		portB = new Port6522();
		portB.setPortMask(0xff);
		matrix.attachToPort(portB, portA);
	}
	
	@Test
	public void testInit()
	{
		portB.writePort(0xff);
		assertEquals(0xff, portA.readPort());
	}

	@Test
	public void testClosedGates()
	{
		for (int i = 0; i < 8; i++)
		{
			portB.writePort(~(1<<i));
			assertEquals(0xff, portA.readPort());
		}
	}
	
	@Test
	public void testReadOneGate()
	{
		matrix.keyDown(3,2);
		portB.writePort(0);
		assertEquals(0xF7, portA.readPort());
		for (int i = 0; i < 8; i++)
		{
			portB.writePort(~(1<<i));
			assertEquals((i == 2) ? 0xF7 : 0xFF, portA.readPort());
		}
	}

	@Test
	public void testReadTwoGates()
	{
		matrix.keyDown(1,2);
		matrix.keyDown(4,3);
		portB.writePort(0);
		assertEquals(0xED, portA.readPort());
		for (int i = 0; i < 8; i++)
		{
			portB.writePort(~(1<<i));
			if (i == 2)
				assertEquals(0xFD, portA.readPort());
			else if (i == 3)
				assertEquals(0xEF, portA.readPort());
			else
				assertEquals(0xFF, portA.readPort());
		}
	}
}
